package com.zpark.user_system.servlet;

import com.zpark.user_system.bean.User;
import com.zpark.user_system.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询用户所有数据
 */
@WebServlet("/user/find_user_all.do")
public class FindAllUserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询用户数据信息
        String userData = "";

        // 根据用户名向数据库查询数据
        Connection conn = null;
        PreparedStatement stat = null;
        ResultSet res = null;

        try {
            // 获取数据库连接对象
            conn = JDBCUtils.getConnection();
            // 编写sql语句
            String sql = "select id, username, password, sex, language, city from user";
            // 获取sql预编译对象
            stat = conn.prepareStatement(sql);
            // 执行sql
            res = stat.executeQuery();
            List<User> users = new ArrayList<>();
            // 获取遍历结果集
            while (res.next()) {
                // 封装每一条用户数据
                User user = new User();
                user.setUsername(res.getString("username"));
                user.setId(res.getInt("id"));
                user.setPassword(res.getString("password"));
                user.setLanguage(res.getString("language"));
                user.setSex(res.getString("sex"));
                user.setCity(res.getString("city"));

                // 将用户数据添加到list集合当中
                users.add(user);
            }

            // 将存放用户集合的对象存放到request对象当中
            request.setAttribute("lists", users);
            // 转发到用户列表页面
            request.getRequestDispatcher("/jsp/user_list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            JDBCUtils.close(conn, stat, res);
        }
    }
}
